from shui.plugin import Plugin
from shui.config import conf
from os import walk, stat
from os.path import join, split, splitext
from logging import critical, warn, debug, info 
import sys
import tagpy
from shui.handlers import DMAPObject, DMAPGeneric
from mimetypes import MimeTypes

item_id_counter = 1

def getinfo(name):
      global item_id_counter
      fd = tagpy.FileRef(name)
      details = fd.tag()
      properties = fd.audioProperties()
      file = split(name)[1]
      basename, songformat = splitext(file)
      curr_itemid = item_id_counter
      item_id_counter = item_id_counter + 1
      file_info = DMAPObject('mlit')
      file_info.addatomic('miid', curr_itemid)
      file_info.addatomic('minm', basename)
      file_info.addatomic('asal', details.album)
      file_info.addatomic('asar', details.artist)
      file_info.addatomic('asfm', songformat[1:])
      file_info.addatomic('astm', int(properties.length*1000))
      sz = stat(name).st_size
      file_info.addatomic('assz', int(sz))
      file_info.addatomic('asgn', details.genre)
      asyr = DMAPGeneric(details.year, 'h')
      file_info.addatomic('asyr', asyr)
      astn = DMAPGeneric(int(details.track), 'h')
      file_info.addatomic('astn', astn)
      file_info = file_info.serialize()[8:]
      return curr_itemid, file_info




class FileSource(Plugin):
      plugin_type = 'file'
      def __init__(self):
            self.playlist_cache = []
            self.song_cache = {}
            try:
                  self.source_path = conf['FileSource']['source_path']
            except:
                  critical('did not find source_path to scan')
                  sys.exit(1)
      def gen_playlist(self):
            import time
            print time.ctime()
            if len(self.playlist_cache) == 0:
                  mt = MimeTypes()
                  lst = {}
                  for root, dirs, files in walk(self.source_path):
                        debug('r:%s d:%s f:%s' % (root, dirs, files))
                        for file in files:
                              name = join(root, file)
                              file_type = mt.guess_type(name)[0]
                              if file_type == 'audio/mpeg' or file_type == 'application/ogg':
                                    itemid, fileinfo = getinfo(name)
                                    self.song_cache[itemid] = name
                                    self.playlist_cache.append(fileinfo)
                  print time.ctime()
                  return self.playlist_cache
            else:
                  print time.ctime()
                  return self.playlist_cache

      def play_item(self, item,  range=0):
            filename = self.song_cache[item]
            fd = open(filename, 'r')
            if range > 0:
                  fd.seek(range)
            itemfile = fd.read()
            print len(itemfile)
            return itemfile
            

if __name__ == '__main__':
      import config
      config.getconfig()
      a = FileSource()
      print a.gen_playlist()
